package com.palace.saw.module.app.service.articlecategory;

import com.palace.saw.framework.common.pojo.PageResult;
import com.palace.saw.framework.common.util.object.BeanUtils;
import com.palace.saw.module.app.controller.admin.articlecategory.vo.ArticleCategoryPageReqVO;
import com.palace.saw.module.app.controller.admin.articlecategory.vo.ArticleCategorySaveReqVO;
import com.palace.saw.module.app.dal.dataobject.articlecategory.ArticleCategoryDO;
import com.palace.saw.module.app.dal.mysql.articlecategory.ArticleCategoryMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import static com.palace.saw.framework.common.exception.util.ServiceExceptionUtil.exception;
import static com.palace.saw.module.app.enums.ErrorCodeConstants.ARTICLE_CATEGORY_NOT_EXISTS;

/**
 * 文章分类 Service 实现类
 *
 * @author saw
 */
@Service
@Validated
public class ArticleCategoryServiceImpl implements ArticleCategoryService {

    @Resource
    private ArticleCategoryMapper articleCategoryMapper;

    @Override
    public Long createArticleCategory(ArticleCategorySaveReqVO createReqVO) {
        // 插入
        ArticleCategoryDO articleCategory = BeanUtils.toBean(createReqVO, ArticleCategoryDO.class);
        articleCategoryMapper.insert(articleCategory);
        // 返回
        return articleCategory.getId();
    }

    @Override
    public void updateArticleCategory(ArticleCategorySaveReqVO updateReqVO) {
        // 校验存在
        validateArticleCategoryExists(updateReqVO.getId());
        // 更新
        ArticleCategoryDO updateObj = BeanUtils.toBean(updateReqVO, ArticleCategoryDO.class);
        articleCategoryMapper.updateById(updateObj);
    }

    @Override
    public void deleteArticleCategory(Long id) {
        // 校验存在
        validateArticleCategoryExists(id);
        // 删除
        articleCategoryMapper.deleteById(id);
    }

    private void validateArticleCategoryExists(Long id) {
        if (articleCategoryMapper.selectById(id) == null) {
            throw exception(ARTICLE_CATEGORY_NOT_EXISTS);
        }
    }

    @Override
    public ArticleCategoryDO getArticleCategory(Long id) {
        return articleCategoryMapper.selectById(id);
    }

    @Override
    public PageResult<ArticleCategoryDO> getArticleCategoryPage(ArticleCategoryPageReqVO pageReqVO) {
        return articleCategoryMapper.selectPage(pageReqVO);
    }

}